package org.elec.mac.inter;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elec.mac.ehcache.CacheConfiguration;
import org.elec.mac.entity.SClientWx;
import org.elec.mac.utils.Utils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@Slf4j
public class InterController {

    @Autowired
    public CacheConfiguration cacheConfiguration;

    /**
     * @param response
     * @param code
     * @param msg
     * @return
     */
    public void responseJson(HttpServletResponse response, int code, String msg, JSONObject body) throws IOException {
        JSONObject result = new JSONObject();
        result.put("code", code);
        result.put("msg", msg);
        if(null != body) {
            result.put("body", body);
        }
        response.setContentType("text/json");
        response.setCharacterEncoding("UTF-8");
        log.info(result.toString());
        response.getWriter().write(result.toString());
    }

    /**
     * @param requestJson
     * @param obj
     * @return
     */
    public Object jsonToObject(JSONObject requestJson, Object obj) {
        if(obj instanceof SClientWx) {
            return this.getSClientWx(requestJson);
        }
        return null;
    }

    /**
     * @param json
     * @return
     */
    public SClientWx getSClientWx(JSONObject json) {
        try {
            if(json.get("openid") != null) {
                SClientWx sClientWx = new SClientWx();
                sClientWx.setOpenid((String) json.get("openid"));
                sClientWx.setNickname(Utils.obj2Array(json.get("nickname")));
                sClientWx.setCity(Utils.obj2String(json.get("city")));
                sClientWx.setProvince(Utils.obj2String(json.get("province")));
                sClientWx.setCountry(Utils.obj2String(json.get("country")));
                sClientWx.setUnionid(Utils.obj2String(json.get("unionid")));
                sClientWx.setSex(Utils.obj2Intger(json.get("sex")));
                sClientWx.setPrivilege("");
                sClientWx.setHeadimgurl(Utils.obj2String(json.get("headimgurl")));
                sClientWx.setLogintime(new Date());
                return sClientWx;
            }
        } catch(Exception ex) {
            log.error("客户信息类型转换异常", ex);
        }

        return null;
    }
}
